package com.huawei.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Arrays;

/**
 * @author wujinpeng
 * @version 1.0
 * @date 2025/2/2 16:49
 * @description Navicat导出密码解密工具类
 */
public class NavicatPassword {
    private int version = 0;
    private static final String aesKey = "libcckeylibcckey";
    private static final String aesIv = "libcciv libcciv ";
    private static final String blowString = "3DC5CA39";
    private byte[] blowKey = null;
    private byte[] blowIv = null;

    public NavicatPassword(int version) {
        this.version = version;
        this.blowKey = sha1(blowString);
        this.blowIv = hex2bin("d9c7c3c8870d64bd");
    }

    // Encrypt method based on version
    public String encrypt(String string) {
        String result = null;
        switch (this.version) {
            case 11:
                result = encryptEleven(string);
                break;
            case 12:
                result = encryptTwelve(string);
                break;
            default:
                break;
        }
        return result;

    }

    // Encrypt method for version 11
    private String encryptEleven(String string) {
        int round = (int) Math.floor(string.length() / 8.0);
        int leftLength = string.length() % 8;
        StringBuilder result = new StringBuilder();
        byte[] currentVector = this.blowIv;

        for (int i = 0; i < round; i++) {
            String temp = encryptBlock(xorBytes(string.substring(8 * i, 8 * (i + 1)), new String(currentVector)));
            currentVector = xorBytes(new String(currentVector), temp);
            result.append(temp);
        }

        if (leftLength > 0) {
            currentVector = encryptBlock(currentVector).getBytes();
            result.append(xorBytes(string.substring(8 * round), new String(currentVector)));
        }

        return bytesToHex(result.toString().getBytes()).toUpperCase();
    }

    // Encrypt block with Blowfish algorithm
    private String encryptBlock(byte[] block) {
        try {
            Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(this.blowKey, "Blowfish");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] encrypted = cipher.doFinal(block);
            return new String(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // Decrypt block with Blowfish algorithm
    private byte[] decryptBlock(String block) {
        try {
            Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(this.blowKey, "Blowfish");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            return cipher.doFinal(block.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // XOR operation between two byte arrays
    private byte[] xorBytes(String str1, String str2) {
        byte[] result = new byte[str1.length()];
        for (int i = 0; i < str1.length(); i++) {
            result[i] = (byte) (str1.charAt(i) ^ str2.charAt(i));
        }
        return result;
    }

    // Encrypt method for version 12 (AES)
    private String encryptTwelve(String string) {
        try {
            IvParameterSpec ivSpec = new IvParameterSpec(aesIv.getBytes());
            SecretKeySpec keySpec = new SecretKeySpec(aesKey.getBytes(), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

            byte[] encrypted = cipher.doFinal(string.getBytes());
            return bytesToHex(encrypted).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // Decrypt method based on version
    public String decrypt(String string) {
        String result = null;
        switch (this.version) {
            case 11:
                result = decryptEleven(string);
                break;
            case 12:
                result = decryptTwelve(string);
                break;
            default:
                break;
        }
        return result;
    }

    // Decrypt method for version 11
    private String decryptEleven(String upperString) {
        byte[] string = hex2bin(upperString.toLowerCase());

        int round = (int) Math.floor(string.length / 8.0);
        int leftLength = string.length % 8;
        StringBuilder result = new StringBuilder();
        byte[] currentVector = this.blowIv;

        for (int i = 0; i < round; i++) {
            byte[] encryptedBlock = Arrays.copyOfRange(string, 8 * i, 8 * (i + 1));
            String temp = new String(xorBytes(new String(decryptBlock(new String(encryptedBlock))), new String(currentVector)));
            currentVector = xorBytes(new String(currentVector), new String(encryptedBlock));
            result.append(temp);
        }

        if (leftLength > 0) {
            currentVector = encryptBlock(currentVector).getBytes();
            result.append(new String(xorBytes(new String(string, 8 * round, leftLength), new String(currentVector))));
        }

        return result.toString();
    }

    // Decrypt method for version 12 (AES)
    private String decryptTwelve(String upperString) {
        byte[] string = hex2bin(upperString.toLowerCase());
        try {
            IvParameterSpec ivSpec = new IvParameterSpec(aesIv.getBytes());
            SecretKeySpec keySpec = new SecretKeySpec(aesKey.getBytes(), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            byte[] decrypted = cipher.doFinal(string);
            return new String(decrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // Convert hexadecimal string to byte array
    private byte[] hex2bin(String hex) {
        int length = hex.length();
        byte[] bytes = new byte[length / 2];
        for (int i = 0; i < length; i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return bytes;
    }

    // SHA1 hash function
    private byte[] sha1(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            return digest.digest(input.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // Convert byte array to hexadecimal string
    private String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static void main(String[] args) {
        // Create NavicatPassword object with version 12
        NavicatPassword navicatPassword = new NavicatPassword(12);

        // Decrypt a given encrypted string
        String decode = navicatPassword.decrypt("503AA930968F877F04770B47DD731DC0");
        System.out.println(decode);
    }
}
